<template>
  <div>
    <el-upload action="#" :file-list="filelist" list-type="picture-card" :class="{show:filelist.length>0}" :limit="1" :on-preview="onPreview" :on-change="onChange" :on-remove="onRemove" :before-upload="beforeUpload" :http-request="upload">
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="showPercent"
      style="width: 146px"
      :text-inside="true"
      :stroke-width="18"
      :percentage="percent"
    />
    <el-dialog :visible="showDialog" @close="outDialog">
      <img style="width:100%;" :src="filelist.length>0 && filelist[0].url" alt="" srcset="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// SecretId: AKIDUmpb6KHxMULwGI3YmQo31j9IBn8C0Xnm

// SecretKey: kDPLzNUKsABvOcaHhqjKenmW0EDwQedN
const cos = new COS({
  SecretId: 'AKIDUmpb6KHxMULwGI3YmQo31j9IBn8C0Xnm',
  SecretKey: 'kDPLzNUKsABvOcaHhqjKenmW0EDwQedN'
})
export default {
  data() {
    return {
      filelist: [],
      showDialog: false,
      percent: 0,
      showPercent: false
    }
  },
  methods: {
    onPreview(file) {
      this.showDialog = true
    },
    outDialog() {
      this.showDialog = false
    },
    onChange(file, newfilelist) {
      this.filelist = newfilelist
    },
    onRemove(file, newfilelist) {
      this.filelist = newfilelist
    },
    beforeUpload(file) {
      // const isJPG = file.type === 'image/png'
      const isIMG = file.type.indexOf('image/') !== -1
      console.log(file.type.indexOf('image'))
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isIMG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isIMG && isLt2M
    },
    upload(params) {
      this.showPercent = true
      cos.putObject({
        Bucket: 'hrsystem-1305868483', // 存储桶
        Region: 'ap-guangzhou', // 地域
        Key: params.file.name, // 文件名
        Body: params.file, // 要上传的文件对象
        StorageClass: 'STANDARD', // 上传的模式类型 直接默认 标准模式即可
        // 上传到腾讯云 =》 哪个存储桶 哪个地域的存储桶 文件  格式  名称 回调
        onProgress: (params) => {
          this.percent = params.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          // 每当上传完毕, 将腾讯云回显的地址放入文件列表中
          this.filelist[0].url = 'http://' + data.Location
          this.filelist[0].status = 'success'
        }
        setTimeout(() => {
          this.showPercent = false
        }, 888)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.show{
 ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
